package tenglang.zuul.service;

import auth.server.impl.service.impl.OauthClientDetailsSerivceImpl;
import auth.server.inter.pojo.OauthClientDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;

@Service
public class ZuulOauthClientSerivce implements ClientDetailsService {


    @Autowired
    private OauthClientDetailsSerivceImpl clientService;


    /**
     * Load a client by the client id. This method must not return null.
     *
     * @param clientId The client id.
     * @return The client details (never null).
     * @throws ClientRegistrationException If the client account is locked, expired, disabled, or invalid for any other reason.
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        OauthClientDetails oauthClientDetails=clientService.findClientsByClientId(clientId);
        BaseClientDetails baseClientDetails=new BaseClientDetails();
        baseClientDetails.setClientId(oauthClientDetails.getClientId());
        baseClientDetails.setClientSecret(new BCryptPasswordEncoder().encode("secret"));
        baseClientDetails.setAccessTokenValiditySeconds(oauthClientDetails.getAccessTokenValidity().intValue());
        baseClientDetails.setRefreshTokenValiditySeconds(oauthClientDetails.getRefreshTokenValidity().intValue());
        if(StringUtils.isNotBlank(oauthClientDetails.getScope())){
            baseClientDetails.setScope(Arrays.asList(oauthClientDetails.getScope().split(",")));
        }
        if(StringUtils.isNotBlank(oauthClientDetails.getAuthorizedGrantTypes())){
            baseClientDetails.setAuthorizedGrantTypes(Arrays.asList(oauthClientDetails.getAuthorizedGrantTypes().split(",")));
        }

        if(StringUtils.isNotBlank(oauthClientDetails.getWebServerRedirectUri())){
            baseClientDetails.setRegisteredRedirectUri(new HashSet(Arrays.asList(oauthClientDetails.getWebServerRedirectUri().split(","))));
        }

        if(oauthClientDetails.getAutoApprove()){
            baseClientDetails.setAutoApproveScopes(Arrays.asList(oauthClientDetails.getScope().split(",")));
        }
        return baseClientDetails;
    }
}
